package com.hava.utils.pattern;

import com.hava.utils.exception.DeveloperException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SingletonManager {

    private static volatile Map<String, Object> holder = new ConcurrentHashMap<>();

    public static synchronized  <T extends Object> T getInstance(Class<T> t_clazz) throws DeveloperException {

        T singleton = (T) holder.get(t_clazz.getName());

        if (singleton == null) {

            synchronized (SingletonManager.class) {
                singleton = (T) holder.get(t_clazz.getName());
                if (singleton == null) {
                    try {
                        singleton = t_clazz.newInstance();
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new DeveloperException(e.toString());
                    }
                    holder.put(t_clazz.getName(), singleton);
                }
            }

        }

        return singleton;
    }
}
